#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

const int num = 5;

void* threadactive(void* args)
{
    string name = static_cast<const char*>(args);

    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        cout << name << " acting..." << endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t th[num];
    for(int i = 0; i < num; i++)
    {
        char* name = new char[64];
        snprintf(name, 64, "thread-%d", i+1);
        pthread_create(&th[i], nullptr, threadactive, (void*)name);
    }

    while(true)
    {
        cout << "main thread wakeup other thread..." << endl;
        //pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    return 0;
}

// 因为开锁的机制不是交换，而是重新赋值，所以可以用其他线程去开别人的锁
// void* threadrun(void* args)
// {
//     cout << "thread running..." << endl;
//     sleep(3);
//     pthread_mutex_lock(&mutex);
//     cout << "thread locked..." << endl;
    
//     pthread_mutex_lock(&mutex);

//     cout << "thread continue..." << endl;

//     return nullptr;
// }

// int main()
// {
//     pthread_t th;
//     pthread_create(&th, nullptr, threadrun, nullptr);

//     sleep(10);

//     pthread_mutex_unlock(&mutex);
//     cout << "thread unlock..." << endl;

//     sleep(10);
//     pthread_join(th, nullptr);

//     return 0;
// }